import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  Plus, 
  Search, 
  Filter, 
  CheckCircle2, 
  Circle, 
  Trash2, 
  Edit3, 
  Calendar, 
  Flag,
  BarChart3,
  Settings,
  Moon,
  Sun,
  Sparkles
} from 'lucide-react';
import TodoForm from './components/TodoForm';
import TodoItem from './components/TodoItem';
import Stats from './components/Stats';
import FilterBar from './components/FilterBar';

const API_BASE = '/api';

function App() {
  const [todos, setTodos] = useState([]);
  const [filteredTodos, setFilteredTodos] = useState([]);
  const [showForm, setShowForm] = useState(false);
  const [editingTodo, setEditingTodo] = useState(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [filter, setFilter] = useState({ category: 'all', priority: 'all', status: 'all' });
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(true);
  const [darkMode, setDarkMode] = useState(true);

  // 获取所有待办事项
  const fetchTodos = async () => {
    try {
      const response = await fetch(`${API_BASE}/todos`);
      const data = await response.json();
      setTodos(data);
      setLoading(false);
    } catch (error) {
      console.error('获取待办事项失败:', error);
      setLoading(false);
    }
  };

  // 获取统计信息
  const fetchStats = async () => {
    try {
      const response = await fetch(`${API_BASE}/stats`);
      if (response.ok) {
        const data = await response.json();
        setStats(data);
      } else {
        console.error('获取统计信息失败:', response.status);
        setStats({ total: 0, completed: 0, pending: 0, highPriority: 0 });
      }
    } catch (error) {
      console.error('获取统计信息失败:', error);
      setStats({ total: 0, completed: 0, pending: 0, highPriority: 0 });
    }
  };

  // 创建待办事项
  const createTodo = async (todoData) => {
    try {
      const response = await fetch(`${API_BASE}/todos`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(todoData)
      });
      
      if (response.ok) {
        fetchTodos();
        fetchStats();
        setShowForm(false);
      }
    } catch (error) {
      console.error('创建待办事项失败:', error);
    }
  };

  // 更新待办事项
  const updateTodo = async (id, todoData) => {
    try {
      const response = await fetch(`${API_BASE}/todos/${id}`, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(todoData)
      });
      
      if (response.ok) {
        fetchTodos();
        fetchStats();
        setEditingTodo(null);
      }
    } catch (error) {
      console.error('更新待办事项失败:', error);
    }
  };

  // 删除待办事项
  const deleteTodo = async (id) => {
    try {
      const response = await fetch(`${API_BASE}/todos/${id}`, {
        method: 'DELETE'
      });
      
      if (response.ok) {
        fetchTodos();
        fetchStats();
      }
    } catch (error) {
      console.error('删除待办事项失败:', error);
    }
  };

  // 切换完成状态
  const toggleComplete = async (todo) => {
    await updateTodo(todo.id, { ...todo, completed: !todo.completed });
  };

  // 过滤和搜索
  useEffect(() => {
    let filtered = todos;

    // 搜索过滤
    if (searchTerm) {
      filtered = filtered.filter(todo => 
        todo.title.toLowerCase().includes(searchTerm.toLowerCase()) ||
        todo.description.toLowerCase().includes(searchTerm.toLowerCase())
      );
    }

    // 分类过滤
    if (filter.category !== 'all') {
      filtered = filtered.filter(todo => todo.category === filter.category);
    }

    // 优先级过滤
    if (filter.priority !== 'all') {
      filtered = filtered.filter(todo => todo.priority === filter.priority);
    }

    // 完成状态过滤
    if (filter.status !== 'all') {
      filtered = filtered.filter(todo => 
        filter.status === 'completed' ? todo.completed : !todo.completed
      );
    }

    setFilteredTodos(filtered);
  }, [todos, searchTerm, filter]);

  useEffect(() => {
    fetchTodos();
    fetchStats();
  }, []);

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <motion.div
          animate={{ rotate: 360 }}
          transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
          className="w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full"
        />
      </div>
    );
  }

  return (
    <div className={`min-h-screen transition-all duration-300 ${
      darkMode 
        ? 'bg-gradient-to-br from-slate-900 via-purple-900 to-slate-900' 
        : 'bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50'
    }`}>
      <div className="container mx-auto px-4 py-6 max-w-4xl">
        {/* 头部 */}
        <motion.header 
          initial={{ y: -20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          className="glass-effect p-6 mb-6 text-center relative overflow-hidden"
        >
          <div className="absolute inset-0 bg-gradient-to-r from-blue-500/10 to-purple-500/10" />
          <div className="relative z-10">
            <motion.div
              animate={{ rotate: [0, 10, -10, 0] }}
              transition={{ duration: 2, repeat: Infinity, repeatDelay: 3 }}
              className="inline-block mb-2"
            >
              <Sparkles className="w-8 h-8 text-yellow-400 mx-auto" />
            </motion.div>
            <h1 className={`text-3xl font-bold mb-2 ${
              darkMode ? 'text-white' : 'text-gray-800'
            }`}>
              酷炫待办事项
            </h1>
            <p className={`${darkMode ? 'text-white/70' : 'text-gray-600'}`}>
              让你的任务管理更加高效和有趣
            </p>
          </div>
          
          {/* 主题切换按钮 */}
          <button
            onClick={() => setDarkMode(!darkMode)}
            className="absolute top-4 right-4 p-2 rounded-lg bg-white/10 hover:bg-white/20 transition-colors"
          >
            {darkMode ? <Sun className="w-5 h-5" /> : <Moon className="w-5 h-5" />}
          </button>
        </motion.header>

        {/* 统计信息 */}
        <Stats stats={stats} darkMode={darkMode} />

        {/* 搜索和过滤 */}
        <motion.div 
          initial={{ y: 20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ delay: 0.2 }}
          className="glass-effect p-4 mb-6"
        >
          <div className="flex flex-col sm:flex-row gap-4 mb-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-white/60" />
              <input
                type="text"
                placeholder="搜索待办事项..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="input-field pl-10 w-full"
              />
            </div>
            <button
              onClick={() => setShowForm(true)}
              className="btn-primary flex items-center gap-2 whitespace-nowrap"
            >
              <Plus className="w-4 h-4" />
              添加任务
            </button>
          </div>
          
          <FilterBar 
            searchTerm={searchTerm}
            setSearchTerm={setSearchTerm}
            filters={filter} 
            setFilters={setFilter} 
            darkMode={darkMode} 
          />
        </motion.div>

        {/* 待办事项列表 */}
        <motion.div
          initial={{ y: 20, opacity: 0 }}
          animate={{ y: 0, opacity: 1 }}
          transition={{ delay: 0.3 }}
        >
          <AnimatePresence mode="popLayout">
            {filteredTodos.length === 0 ? (
              <motion.div
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                className="glass-effect p-8 text-center"
              >
                <Circle className="w-16 h-16 text-white/30 mx-auto mb-4" />
                <p className={`text-lg ${darkMode ? 'text-white/70' : 'text-gray-600'}`}>
                  {searchTerm || filter.category !== 'all' || filter.priority !== 'all' || filter.status !== 'all'
                    ? '没有找到匹配的待办事项'
                    : '还没有待办事项，点击上方按钮添加一个吧！'
                  }
                </p>
              </motion.div>
            ) : (
              <div className="space-y-3">
                {filteredTodos.map((todo, index) => (
                  <TodoItem
                    key={todo.id}
                    todo={todo}
                    index={index}
                    onToggleComplete={toggleComplete}
                    onEdit={setEditingTodo}
                    onDelete={deleteTodo}
                    darkMode={darkMode}
                  />
                ))}
              </div>
            )}
          </AnimatePresence>
        </motion.div>

        {/* 添加/编辑表单 */}
        <AnimatePresence>
          {(showForm || editingTodo) && (
            <TodoForm
              todo={editingTodo}
              onSubmit={editingTodo ? 
                (data) => updateTodo(editingTodo.id, data) : 
                createTodo
              }
              onClose={() => {
                setShowForm(false);
                setEditingTodo(null);
              }}
              darkMode={darkMode}
            />
          )}
        </AnimatePresence>
      </div>
    </div>
  );
}

export default App;